/**
 * ES6写法的JSBridge
 *
 * @export
 * @class JSBridge
 */
import {
  Dialog
} from 'vant'

export default class JSBridge {
  constructor () {
    this.name = 'JSBridge'
    this.reset = true
    this.instance = null
  }

  static getInstance () {
    if (!this.instance) {
      this.instance = new JSBridge()
    }
    return this.instance
  }

  /**
   * 判断设备类型
   *
   * @returns
   * @memberof JSBridge
   */
  device () {
    var u = navigator.userAgent
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
    // eslint-disable-next-line
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
    return isAndroid
  }

  /**
   * JSBridge初始化
   *
   * @param {*} callback
   * @returns
   * @memberof JSBridge
   */
  _init (callback) {
    const isAn = this.device()
    if (isAn) {
      if (window.WebViewJavascriptBridge) {
        // eslint-disable-next-line
        callback(WebViewJavascriptBridge)
      } else {
        document.addEventListener(
          'WebViewJavascriptBridgeReady',
          function () {
            // eslint-disable-next-line
            callback(WebViewJavascriptBridge)
          },
          false
        )
      }
      return
    }

    if (window.WebViewJavascriptBridge) {
      // eslint-disable-next-line
      return callback(WebViewJavascriptBridge)
    }
    if (window.WVJBCallbacks) {
      return window.WVJBCallbacks.push(callback)
    }
    window.WVJBCallbacks = [callback]
    var WVJBIframe = document.createElement('iframe')
    WVJBIframe.style.display = 'none'
    WVJBIframe.src = 'wvjbscheme://__bridge_loaded__'
    document.documentElement.appendChild(WVJBIframe)
    setTimeout(function () {
      document.documentElement.removeChild(WVJBIframe)
    }, 0)
  }

  /**
   * 安卓设备的初始化
   * @param {*} bridge
   */
  __init__ (bridge) {
    const isAn = this.device()
    if (this.reset && isAn) {
      this.reset = false
      bridge.init(function (message, responseCallback) {
        console.log('JS got a message', message)
        var data = {
          'Javascript Responds': '测试中文!'
        }
        console.log('JS responding with', data)
        responseCallback(data)
      })
    }
  }

  /**
   * 获取用户信息
   *
   * @param {*} data
   * @param {*} callback
   * @memberof JSBridge
   */
  getUserInfo (data, callback) {
    this._init(function (bridge) {
      this.__init__(bridge)
      bridge.callHandler('getUserInfo', data, function (response) {
        console.log(response)
        callback(formatParseJson(response))
      })
    }.bind(this))
  }

  jsEcho (callback) {
    this._init(function (bridge) {
      this.__init__(bridge)
      bridge.registerHandler('JS Echo', function (data, responseCallback) {
        console.log('JS Echo called with:', data)
        responseCallback(callback(formatParseJson(data)))
      })
    }.bind(this))
  }

  /**
   * 原生界面的万能跳转
   * @param {*} iOSParams
   * @param {*} AndroidParams
   * @param {*} callback
   */
  nativePush (iOSParams, AndroidParams, callback) {
    console.log('调用nativePush')
    this._init(function (bridge) {
      console.log(bridge)
      this.__init__(bridge)
      const isAndroid = this.device()
      const params = isAndroid ? AndroidParams : iOSParams
      console.log(params)
      bridge.callHandler('nativePush', params, function (responseData) {
        console.log(responseData)
        callback()
      })
    }.bind(this))
  }

  /**
   * 原生调起H5购物车的编辑状态
   * @param {*} callback
   */
  shopCartEdit (callback) {
    this._init(function (bridge) {
      this.__init__(bridge)
      bridge.registerHandler('shopCartEdit', (data) => {
        console.log('购物车编辑回调: ', data)
        callback(formatParseJson(data))
      })
    }.bind(this))
  }

  /**
   * 导航栏上新增收货地址动作
   * @param {*} callback
   */
  addAddress (callback) {
    this._init(function (bridge) {
      this.__init__(bridge)
      bridge.registerHandler('addAddress', (data, responseCallback) => {
        console.log('新增收货地址回调: ', data)
        responseCallback(callback(data))
      })
    }.bind(this))
  }

  /**
   * 导航栏上删除收货地址动作
   * @param {*} callback
   */
  deleteAddress (callback) {
    this._init(function (bridge) {
      this.__init__(bridge)
      bridge.registerHandler('deleteAddress', (data, responseCallback) => {
        console.log('删除收货地址回调: ', data)
        responseCallback(callback(data))
      })
    }.bind(this))
  }

  /**
   * 从原生获取登录令牌
   * @param {*} callback
   */
  getAccessToken (callback) {
    if (process.env.NODE_ENV === 'development') {
      setTimeout(function () {
        callback(process.env.ACCESS_TOKEN)
      }, process.env.LOADING_TIME)
    } else {
      this._init(function (bridge) {
        this.__init__(bridge)
        bridge.callHandler('getAccessToken', {}, function (response) {
          console.log(response)
          callback(formatParseJson(response).accessToken)
          // callback(response)
        })
      }.bind(this))
    }
  }

  /**
   * 显示支付弹框 选择支付方式
   * @param {*} callback
   */
  showPaymentControl (data, callback) {
    if (process.env.NODE_ENV === 'development') {
      setTimeout(function () {
        let response = {
          status: false
        }
        callback(response)
      }, process.env.LOADING_TIME)
    } else {
      this._init(function (bridge) {
        this.__init__(bridge)
        bridge.callHandler('showPaymentControl', data, function (response) {
          callback(response)
        })
      }.bind(this))
    }
  }

  /**
   *  关闭支付弹窗回调
   * @param {*} callback
   */
  closePaymentControl (callback) {
    this._init(function (bridge) {
      this.__init__(bridge)
      bridge.registerHandler('closePaymentControl', () => {
        console.log('关闭支付弹窗回调')
        callback()
      })
    }.bind(this))
  }

  /**
   * 调用原生confirm弹框
   * @param {*} callback
   */
  showConfirmControl (data, callback) {
    if (process.env.NODE_ENV === 'development') {
      setTimeout(() => {
        Dialog.confirm({
          title: '标题',
          message: '弹窗内容'
        }).then(() => {
          // on confirm
          callback()
        }).catch(() => {
          // on cancel
          console.log('catch')
        })
      }, process.env.LOADING_TIME)
    } else {
      this._init(function (bridge) {
        this.__init__(bridge)
        bridge.callHandler('showConfirmControl', data, function (response) {
          callback(response)
        })
      }.bind(this))
    }
  }

  /**
   * iOS监听加载成功
   * @param {*} callback
   */
  finishLoaded (callback) {
    this._init(function (bridge) {
      this.__init__(bridge)
      bridge.callHandler('finishLoaded', {}, function (response) {
        callback()
      })
    }.bind(this))
  }

  /**
   * 配置右上角按钮
   * @param {*} data
   * @param {*} callback
   */
  configRightBar (data, callback) {
    this._init(function (bridge) {
      this.__init__(bridge)
      bridge.callHandler('configRightBar', data, function (response) {
        callback()
      })
    }.bind(this))
  }

  /**
   * 给原生发送分享数据
   * @param {*} data
   * @param {*} callback
   */
  share (data, callback) {
    this._init(function (bridge) {
      this.__init__(bridge)
      bridge.callHandler('share', data, function (res) {
        callback()
      })
    }.bind(this))
  }

  /**
   * 完成支付
   * @param {*} data
   * @param {*} callback
   */
  finishPay (data, callback) {
    console.log('finishpay start')
    this._init(function (bridge) {
      this.__init__(bridge)
      console.log(bridge)
      bridge.registerHandler('finishPay', function (data, responseCallback) {
        console.log('支付完成回调')
        callback()
      })
    }.bind(this))
  }

  /**
   * 跳转到登录界面
   * @param {*} data
   * @param {*} callback
   */
  goToLoginPage (data, callback) {
    this._init(function (bridge) {
      this.__init__(bridge)
      bridge.callHandler('goToLoginPage', data, function (res) {
        callback()
      })
    }.bind(this))
  }

  /**
   * 跳转到老师详情页
   * @param {*} data
   * @param {*} callback
   */
  goToTeacherPage (data, callback) {
    this._init(function (bridge) {
      this.__init__(bridge)
      bridge.callHandler('goToTeacherPage', data, function (res) {
        callback()
      })
    }.bind(this))
  }
}

/**
 * 格式化解析内容为JSON对象
 * @param {*} data
 */
export const formatParseJson = (data) => {
  if (typeof data === 'object' && data.constructor === Object) {
    return data
  } else {
    return JSON.parse(data)
  }
}
